﻿using Newtonsoft.Json;
using SMTUploadProductionData.model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SMTUploadProductionData
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        ReadWriteDatabase readWrite;
        string str_ConnectData;
        string gkg_FilePath = @"C:\Users\Administrator\Desktop\机台数据\GKG印刷机\";
        string juki_FilePath = @"C:\Users\Administrator\Desktop\机台数据\juki贴片\";
        string hl_FilePath = @"C:\Users\Administrator\Desktop\机台数据\回流焊接\";
        string ymh_FilePath = @"C:\Users\Administrator\Desktop\机台数据\雅马哈\";
        private void MainForm_Load(object sender, EventArgs e)
        {
            readWrite = new ReadWriteDatabase(ref str_ConnectData);
            if (str_ConnectData != null)
            {
                textBox1.Text = str_ConnectData;
                return;
            }
            Task.Run(() => gkg_ReadOPEvent());
            Task.Run(() => gkg_ReadData());
            Task.Run(() => gkg_ReadEvent());

            Task.Run(() => Juki_ReadData());
            Task.Run(() => hl_ReadData());
            Task.Run(() => ymh_ReadData());
            Task.Run(() => TextBoxContent());

            Task.Run(() => GKG_PowerDataUpload());
            Task.Run(() => HL_PowerDataUpload());
            Task.Run(() => JUKI_PowerDataUpload());
            Task.Run(() => YMH_PowerDataUpload());

            Task.Run(()=> DataAnalysis());
        }

        #region  gkg数据上传
        private async Task gkg_ReadData()
        {
            while (true)
            {
                try
                {
                    List<string> list_gkg_FilePath = GetgkgFilePath(gkg_FilePath);
                    //遍历当天文件
                    foreach (var item in list_gkg_FilePath)
                    {
                        List<int> list_MaxValue = new List<int>();
                        int Number = 0;
                        //文件具体名称
                        string gkg_FileName = $"{item}\\{DateTime.Now.ToString("yyyy-MM-dd")}.csv";
                        string machineName = item.Replace("\\", ",").Split(',')[item.Replace("\\", ",").Split(',').Length - 1].Replace("  ", ",").Split(',')[0];
                        //如果文件文件不存在就停止
                        if (!File.Exists(gkg_FileName)) continue;
                        //读取文件内容
                        string[] Content = File.ReadAllLines(gkg_FileName, Encoding.GetEncoding("GBK"));
                        for (int i = 1; i < Content.Length; i++)
                        {
                            string[] Array = Content[i].Split(',');
                            int PCBNumber = 0;
                            if (int.Parse(Array[4]) - int.Parse(Content[1].Split(',')[4]) >= 0)
                            {
                                PCBNumber = int.Parse(Content[i].Split(',')[4]) - int.Parse(Content[1].Split(',')[4]);
                                list_MaxValue.Add(PCBNumber);
                            }
                            else
                            {
                                PCBNumber = int.Parse(Array[4]) + list_MaxValue.Max();
                            }
                            gkg_model gkg_data = new gkg_model();
                            gkg_data.MachineName = machineName;
                            gkg_data.BarCode = Array[0];
                            gkg_data.TimeStamp = Array[1];
                            gkg_data.FileName = Array[2];
                            gkg_data.ProgramRunning = Array[3];
                            gkg_data.PCBNumber = PCBNumber;
                            gkg_data.ProdName = Array[5];
                            gkg_data.ProdType = Array[6];
                            gkg_data.CycleTime = Array[7];
                            gkg_data.SPIResult = Array[8];
                            gkg_data.PrintSpeed = Array[9];
                            gkg_data.FrontSQGPress = Array[10];
                            gkg_data.RearSQGPress = Array[11];
                            gkg_data.PrintMode = Array[12];
                            gkg_data.PrintGap = Array[13];
                            gkg_data.SnapOffDistance = Array[14];
                            gkg_data.SnapOffSpeed = Array[15];
                            gkg_data.SnapOffDelay = Array[16];
                            gkg_data.SQGUpSpeed = Array[17];
                            gkg_data.SQGDownSpeed = Array[18];
                            gkg_data.SQGUpFirst = Array[19];
                            gkg_data.SQGHeightAtSnapOff = Array[20];
                            gkg_data.CleaningAfterLastBoard = Array[21];
                            gkg_data.CleaningFrequency = Array[22];
                            gkg_data.CleaningSpeed = Array[23];
                            gkg_data.CleaningMode = Array[24];
                            gkg_data.CleaningType = Array[25];
                            gkg_data.AddSPMode = Array[26];
                            gkg_data.AddSPAfterLastBoard = Array[27];
                            gkg_data.DSPIResult = Array[28];
                            gkg_data.PrintDirection = Array[29];
                            gkg_data.PCBSize = Array[30];
                            if (await readWrite.QueryData("gkg_Producedate", "TimeStamp", gkg_data.TimeStamp, "MachineName", gkg_data.MachineName) == "")
                            {
                                //插入数据库
                                await readWrite.InsertDatabase(gkg_data, "gkg_Producedate");
                                Number++;
                            }
                        }
                        if (Number != 0) OperationLog($"上传gkg:{machineName} {Number}条", textBox1);
                    }
                    OperationLog("线程1运行中(gkg)", textBox2);
                }
                catch (Exception ex)
                {
                    ErrorRecord(ex.ToString() + "      " + "1");
                    continue;
                }
                await Task.Delay(5000);
            }
        }

        /// <summary>
        /// 操作事件记录上传
        /// </summary>
        /// <returns></returns>
        private async Task gkg_ReadEvent()
        {
            while (true)
            {
                //获取文件位置
                List<string> list_gkg_EventFilePath = GetgkgFilePath(gkg_FilePath);
                foreach (var FilePath in list_gkg_EventFilePath)//遍历文件位置、名称
                {
                    int strip = 0;//记录上传数据
                    string gkg_EventFileName = $"{FilePath}\\event.alm";//事件记录文件
                    string machineName = FilePath.Replace("\\", ",").Split(',')[FilePath.Replace("\\", ",").Split(',').Length - 1].Replace("  ", ",").Split(',')[0];//机台名称
                    if (!File.Exists(gkg_EventFileName)) continue;//判断文件是否存在
                    string[] Content = File.ReadAllLines(gkg_EventFileName, Encoding.GetEncoding("GBK"))[0].Replace(DateTime.Now.ToString("yyyy"), $"^{DateTime.Now.ToString("yyyy")}").Split('^');//读取文件内容
                    for (int i = 1; i < Content.Length; i++)
                    {
                        try
                        {
                            string[] ArrayEvent = Content[i].Replace("  ", " ").Split(' ');//拆分每个时间段的事件内容
                            gkg_Event_model Event = new gkg_Event_model();
                            Event.MachineName = machineName;
                            Event.Event_Data = ArrayEvent[0];
                            Event.Event_Time = ArrayEvent[1];
                            Event.Event_Content = ArrayEvent[2];
                            //判断内容在数据库中是否存在
                            if (await readWrite.QueryData("gkg_Event", "Event_Time", Event.Event_Time, "MachineName", Event.MachineName) == "")
                            {
                                //插入数据库
                                await readWrite.InsertDatabase(Event, "gkg_Event");
                                strip++;
                            }
                        }
                        catch (Exception){ continue; }
                    }
                    if (strip != 0) OperationLog($"上传gkg_Event:{machineName} {strip}条", textBox1);
                }
                OperationLog("线程1_1运行中(gkg_Event)", textBox2);
                await Task.Delay(5000);
            }
        }

        /// <summary>
        /// 报警事件记录上传
        /// </summary>
        /// <returns></returns>
        private async Task gkg_ReadOPEvent()
        {
            while (true)
            {
                //获取文件位置
                List<string> list_gkg_OPEventFilePath = GetgkgFilePath(gkg_FilePath);
                foreach (var FilePath in list_gkg_OPEventFilePath)
                {
                    int strip = 0;//记录上传数据
                    string year = DateTime.Now.Year.ToString();
                    string gkg_EventFileName = $"{FilePath}\\OPEvent.txt";//事件记录文件
                    string machineName = FilePath.Replace("\\", ",").Split(',')[FilePath.Replace("\\", ",").Split(',').Length - 1].Replace("  ", ",").Split(',')[0];//机台名称
                    string[] line = File.ReadAllLines(gkg_EventFileName, Encoding.GetEncoding("GBK"))[0].Replace(year, $"^{year}").Split('^');//读取文件内容
                    for (int i = 1; i < line.Length - 1; i++)
                    {
                        try
                        {
                            string[] ArrayOPEvent = line[i].Replace("  ", " ").Split(' ');
                            gkg_OPEvent OPEvent = new gkg_OPEvent();
                            OPEvent.MachineName = machineName;
                            OPEvent.Event_Data = ArrayOPEvent[0];
                            OPEvent.Event_Time = ArrayOPEvent[1];
                            OPEvent.Event_Content = ArrayOPEvent[2];
                            //判断内容在数据库中是否存在
                            if (await readWrite.QueryData("gkg_OPEvent", "Event_Time", OPEvent.Event_Time, "MachineName", OPEvent.MachineName) == "")
                            {
                                //插入数据库
                                await readWrite.InsertDatabase(OPEvent, "gkg_OPEvent");
                                strip++;
                            }
                        }
                        catch (Exception){continue;}
                    }
                    if (strip != 0) OperationLog($"上传gkg_OPEvent:{machineName} {strip}条", textBox1);
                }
                OperationLog("线程1_2运行中(gkg_OPEvent)", textBox2);
                await Task.Delay(1000);
            }
        }

        private List<string> GetgkgFilePath(string filepath)
        {
            List<string> list_Documents = new List<string>();
            //判断文件是否存在
            if (!Directory.Exists(filepath)) return list_Documents;
            //获取文件夹里的文件
            string[] DocumentsName = Directory.GetDirectories(filepath);
            //遍历所有文件
            foreach (var Name in DocumentsName)
            {
                //判断文件是否是今天的日期
                if (Name.Replace("  ", ",").Split(',')[1] == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    //添加到list
                    list_Documents.Add(Name);
                }
            }
            return list_Documents;//返回当天的记录文件名称
        }
        #endregion

        #region  juki数据上传
        /// <summary>
        /// 获取juki贴片机的数据，写入数据库
        /// </summary>
        private async Task Juki_ReadData()
        {
            while (true)
            {
                try
                {
                    //获取文件名称
                    List<string> juki_FilePath = GetjukiFilePath();
                    foreach (var item in juki_FilePath)
                    {
                        try
                        {
                            int Number = 0;
                            //获取文件位置和文件名称
                            string[] juki_FileName = Directory.GetFiles(item);
                            foreach (var FileName in juki_FileName)
                            {
                                //判断文件是否存在
                                if (!File.Exists(FileName)) continue;
                                //获取机台名称
                                string str_MachineName = FileName.Replace("\\", ",").Split(',')[FileName.Replace("\\", ",").Split(',').Length - 3];
                                //获取数据文件名称
                                string str_Name = Path.GetFileName(FileName);
                                //获取产品型号
                                string str_model = str_Name.Split('.')[0];
                                //读取json文件
                                string json_Content = File.ReadAllText(FileName);
                                juki_model juki_Data = JsonConvert.DeserializeObject<juki_model>(json_Content);
                                juki_Data.MachineName = str_MachineName;
                                juki_Data.model = str_model;
                                juki_Data.jsonFileName = str_Name;
                                Number += await readWrite.InsertJukiData(juki_Data);
                            }
                            if (Number != 0)
                            {
                                OperationLog($"已上传{item.Replace("\\", ",").Split(',')[item.Replace("\\", ",").Split(',').Length - 2]}   {Number}条数据", textBox1);
                            }
                        }
                        catch (Exception ex)
                        {
                            ErrorRecord(ex.ToString() + "           2");
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ErrorRecord(ex.ToString() + "           2");
                    continue;
                }
                OperationLog("线程2运行中(juki)", textBox2);
                await Task.Delay(10000);
            }
        }

        /// <summary>
        /// 获取文件位置、名称
        /// </summary>
        /// <returns></returns>
        private List<string> GetjukiFilePath()
        {
            List<string> lsit_Documents = new List<string>();
            string juki_AllDocuments = juki_FilePath;
            if (!Directory.Exists(juki_AllDocuments)) return lsit_Documents;
            string[] juki_ModelName = Directory.GetDirectories(juki_AllDocuments);
            foreach (var model in juki_ModelName)
            {
                if (!Directory.Exists(model)) return lsit_Documents;
                string[] juki_DocumentsName = Directory.GetDirectories(model);
                foreach (var Documents in juki_DocumentsName)
                {
                    if (Path.GetFileName(Documents) == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        lsit_Documents.Add(Documents);
                    }
                }
            }
            return lsit_Documents;
        }
        #endregion

        #region  回流焊接
        private async Task hl_ReadData()
        {
            while (true)
            {
                try
                {
                    //获取文件位置
                    List<string> list_hl_FilePath = GethlFilePath();
                    foreach (var FilePath in list_hl_FilePath)
                    {
                        int Number = 0;
                        //判断文件是否存在
                        if (!File.Exists(FilePath)) continue;
                        //获取机台名称
                        string str_MachineName = Path.GetDirectoryName(FilePath).Replace("\\", ";").Split(';')[Path.GetDirectoryName(FilePath).Replace("\\", ";").Split(';').Length - 1];
                        //读取文件内容
                        string[] hl_Content = File.ReadAllLines(FilePath, Encoding.GetEncoding("GBK"));
                        for (int i = 0; i < hl_Content.Length; i++)
                        {
                            //从"时间"开始到空白行作为一条数据
                            if (hl_Content[i].Contains("时间"))
                            {
                                try
                                {
                                    hl_model hl_Reflow = new hl_model();
                                    hl_Reflow.MachineName = str_MachineName;
                                    hl_Reflow.logTime = hl_Content[i].Replace(": ", ";").Split(';')[1];
                                    if (await readWrite.QueryData("hl_Producedate", "logTime", hl_Reflow.logTime, "MachineName", hl_Reflow.MachineName) != "") continue;
                                    hl_Reflow.PowerSupply = hl_Content[i + 1].Split(':')[1].Trim();
                                    hl_Reflow.Machine = hl_Content[i + 2].Split(':')[1].Trim();
                                    hl_Reflow.HotAirMotor = hl_Content[i + 3].Split(':')[1].Trim();
                                    hl_Reflow.TransportSpeed = hl_Content[i + 4].Split(':')[1].Trim();
                                    hl_Reflow.TrackAlarm = hl_Content[i + 5].Split(':')[1].Trim();
                                    hl_Reflow.UpperFurnaceChamber = hl_Content[i + 6].Split(':')[1].Trim();
                                    hl_Reflow.EmergencyBrake = hl_Content[i + 7].Split(':')[1].Trim();
                                    hl_Reflow.UpperChannel1 = hl_Content[i + 8].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage1 = hl_Content[i + 9].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel2 = hl_Content[i + 10].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage2 = hl_Content[i + 11].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel3 = hl_Content[i + 12].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage3 = hl_Content[i + 13].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel4 = hl_Content[i + 14].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage4 = hl_Content[i + 15].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel5 = hl_Content[i + 16].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage5 = hl_Content[i + 17].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel6 = hl_Content[i + 18].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage6 = hl_Content[i + 19].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel7 = hl_Content[i + 20].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage7 = hl_Content[i + 21].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel8 = hl_Content[i + 22].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage8 = hl_Content[i + 23].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel9 = hl_Content[i + 24].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage9 = hl_Content[i + 25].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel10 = hl_Content[i + 26].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage10 = hl_Content[i + 27].Split(',')[2].Split(':')[1];
                                    hl_Reflow.Fan1 = int.Parse(hl_Content[i + 28].Split(':')[1].Trim());
                                    hl_Reflow.Fan2 = int.Parse(hl_Content[i + 29].Split(':')[1].Trim());
                                    hl_Reflow.ChainSpeedSetting = (int)Math.Round(double.Parse(hl_Content[i + 30].Split(':')[1].Trim()));
                                    hl_Reflow.OxygenConcentration = hl_Content[i + 31].Split(':')[1].Trim();

                                    await readWrite.InsertDatabase(hl_Reflow, "hl_Producedate");
                                    Number++;
                                }
                                catch (Exception ex)
                                {
                                    if (ex.ToString().Contains("输入字符串的格式不正确") || ex.ToString().Contains("索引超出了数组界限")) continue;
                                    ErrorRecord(ex.ToString() + i.ToString() + "           3");
                                    await Task.Delay(10000);
                                    continue;
                                }
                            }
                        }
                        if (Number != 0)
                        {
                            OperationLog($"已上传回流焊接{str_MachineName}   {Number}条数据", textBox1);
                        }
                    }
                    OperationLog("线程3运行中(hl)", textBox2);
                    await Task.Delay(10000);
                }
                catch (Exception)
                {
                    await Task.Delay(10000);
                    continue;
                }
               
            }
        }

        /// <summary>
        /// 获取文件位置、名称
        /// </summary>
        /// <returns></returns>
        private List<string> GethlFilePath()
        {
            List<string> list_hl_Documents = new List<string>();
            try
            {
                if (!Directory.Exists(hl_FilePath)) return list_hl_Documents;
                string[] hl_ModelName = Directory.GetDirectories(hl_FilePath);
                foreach (var ModelName in hl_ModelName)
                {
                    string[] hl_FileName = Directory.GetFiles(ModelName);
                    foreach (var FileName in hl_FileName)
                    {
                        if (Path.GetFileName(FileName) == $"Tmp{DateTime.Now.ToString("yyyy-MM-dd")}.txt")
                        {
                            list_hl_Documents.Add(FileName);
                        }
                    }
                }
            }
            catch (Exception )
            {
                return list_hl_Documents;
            }
            
            return list_hl_Documents;
        }


        #endregion

        #region  雅马哈贴片数据上传
        private async Task ymh_ReadData()
        {
            while (true)
            {
                try
                {
                    //获取文件位置
                    List<string> list_ymh_FilePath = GetymhFilePath();
                    foreach (var FilePath in list_ymh_FilePath)
                    {
                        int Number = 0;
                        //判断文件是否存在
                        if (!File.Exists(FilePath)) continue;
                        //读取文件内容
                        string[] ymh_Content = File.ReadAllLines(FilePath, Encoding.GetEncoding("GBK"));
                        //获取机台名称
                        string ymh_MachineName = "雅马哈_" + Path.GetFileName(FilePath).Split('-')[0];
                        //查询数据库当天ymh_MachineName名称的数据数量
                        int RowData = await readWrite.RowNumber("ymh_Producedate", ymh_MachineName, "Time", ymh_MachineName);
                        if (RowData == ymh_Content.Length) continue;
                        //要插入的数据的数量=文件内容的长度-数据库的长度
                        int row = ymh_Content.Length - (ymh_Content.Length - RowData) - 10;
                       
                        if (row > 100)
                        {
                            for (int i = row; i < ymh_Content.Length; i++)
                            {
                                try
                                {
                                    //拆分数据
                                    string[] str_Array = ymh_Content[i].Split(',');
                                    int number;
                                    ymh_model ymh_Patch = new ymh_model();
                                    ymh_Patch.MachineName = ymh_MachineName;
                                    ymh_Patch.RunningStatus = str_Array[0];
                                    ymh_Patch.ProductName = str_Array[1];
                                    if (str_Array[2].Contains("秒"))
                                    {
                                        str_Array[2] = str_Array[2].Split('.')[0];
                                    }
                                    ymh_Patch.Cycle = int.Parse(str_Array[2]);
                                    ymh_Patch.TotalQuantity = str_Array[3];
                                    if (int.TryParse(str_Array[4], out number))
                                    {
                                        ymh_Patch.NumberBoards = number;
                                    }
                                    else
                                    {
                                        ymh_Patch.NumberBoards = 0;
                                    }
                                    number = 0;
                                    if (int.TryParse(str_Array[5], out number))
                                    {
                                        ymh_Patch.TotalNumber = number;
                                    }
                                    else
                                    {
                                        ymh_Patch.TotalNumber = 0;
                                    }
                                    ymh_Patch.Time = str_Array[6];
                                    string Query = $"select * from ymh_Producedate where MachineName ='{ymh_Patch.MachineName}' and ProductName='{ymh_Patch.ProductName}' " +
                                        $"and Cycle ={ymh_Patch.Cycle} and TotalQuantity ='{ymh_Patch.TotalQuantity}' and NumberBoards ={ymh_Patch.NumberBoards} and TotalNumber ={ymh_Patch.TotalNumber} " +
                                        $"and CAST(Time as date)=CAST(GETDATE() as date)";
                                    //判断数据是否存在数据库中
                                    if (await readWrite.QueryData(Query))
                                    {
                                        //如果不存在就写入数据库
                                        await readWrite.InsertDatabase(ymh_Patch, "ymh_Producedate");
                                        Number++;
                                    }
                                }
                                catch (Exception)
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            for (int i = 0; i < ymh_Content.Length; i++)
                            {
                                try
                                {
                                    //拆分数据
                                    string[] str_Array = ymh_Content[i].Split(',');
                                    int number;
                                    ymh_model ymh_Patch = new ymh_model();
                                    ymh_Patch.MachineName = ymh_MachineName;
                                    ymh_Patch.RunningStatus = str_Array[0];
                                    ymh_Patch.ProductName = str_Array[1];
                                    if (str_Array[2].Contains("秒"))
                                    {
                                        str_Array[2] = str_Array[2].Split('.')[0];
                                    }
                                    ymh_Patch.Cycle = int.Parse(str_Array[2]);
                                    ymh_Patch.TotalQuantity = str_Array[3];
                                    if (int.TryParse(str_Array[4], out number))
                                    {
                                        ymh_Patch.NumberBoards = number;
                                    }
                                    else
                                    {
                                        ymh_Patch.NumberBoards = 0;
                                    }
                                    number = 0;
                                    if (int.TryParse(str_Array[5], out number))
                                    {
                                        ymh_Patch.TotalNumber = number;
                                    }
                                    else
                                    {
                                        ymh_Patch.TotalNumber = 0;
                                    }
                                    ymh_Patch.Time = str_Array[6];
                                    string Query = $"select * from ymh_Producedate where MachineName ='{ymh_Patch.MachineName}' and ProductName='{ymh_Patch.ProductName}' " +
                                        $"and Cycle ={ymh_Patch.Cycle} and TotalQuantity ='{ymh_Patch.TotalQuantity}' and NumberBoards ={ymh_Patch.NumberBoards} and TotalNumber ={ymh_Patch.TotalNumber} " +
                                        $"and CAST(Time as date)=CAST(GETDATE() as date)";
                                    //判断数据是否存在数据库中
                                    if (await readWrite.QueryData(Query))
                                    {
                                        //如果不存在就写入数据库
                                        await readWrite.InsertDatabase(ymh_Patch, "ymh_Producedate");
                                        Number++;
                                    }
                                }
                                catch (Exception)
                                {
                                    continue;
                                }
                            }
                        }

                        if (Number != 0)
                        {
                            OperationLog($"已上传{ymh_MachineName}   {Number}条数据", textBox1);
                        }
                        OperationLog("线程4运行中(ymh)", textBox2);
                    }
                }
                catch (Exception ex)
                {
                    ErrorRecord(ex.ToString() + "           4");
                    await Task.Delay(1000);
                    continue;
                }
                await Task.Delay(1000);
            }
        }

        /// <summary>
        /// 获取文件位置、名称
        /// </summary>
        /// <returns></returns>
        private List<string> GetymhFilePath()
        {
            List<string> list_ymh_Documents = new List<string>();
            //判断文件夹是否存在
            if (!Directory.Exists(ymh_FilePath)) return list_ymh_Documents;
            //读取文件夹的子目录
            string[] ymh_ModelName = Directory.GetDirectories(ymh_FilePath);
            foreach (var ModelName in ymh_ModelName)
            {
                //获取文件夹的名称
                string str_date = ModelName.Replace("\\", ";").Split(';')[ModelName.Replace("\\", ";").Split(';').Length - 1];
                //判断是否是当天的日期
                if (str_date == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    //获取文件夹的文件
                    string[] FileName = Directory.GetFiles(ModelName);
                    if (FileName.Length > 6)
                    {
                        DeleteFile(FileName, str_date);
                    }
                    foreach (var name in FileName)
                    {
                        //将文件名称位置添加到list
                        list_ymh_Documents.Add(name);
                    }
                }
            }
            return list_ymh_Documents;
        }


        /// <summary>
        /// 计算白班产量
        /// </summary>
        /// <returns></returns>
        private async Task GetDayShiftData()
        {
            //白班数据
            List<string> list_DayShift = new List<string>();
            //获取白班数据文件位置名称
            List<string> list_ymh_FileName = GetymhFilePath();
            foreach (var FileName in list_ymh_FileName)
            {
                //清除数据
                list_DayShift.Clear();
                //读取文件内容
                string[] ymh_Content = File.ReadAllLines(FileName, Encoding.GetEncoding("GBK"));
                //机台名称
                string ymh_MachineName = "雅马哈_" + Path.GetFileName(FileName).Split('-')[0];
                foreach (var Content in ymh_Content)
                {
                    //白班开始时间
                    DateTime StaTime = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd 08:00:00"));
                    //白班结束时间
                    DateTime EndTime = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd 21:00:00"));
                    //文件数据记录时间
                    DateTime data_time = DateTime.Parse(Content.Split(',')[6]);
                    //判断数据是否在这个时间
                    if (data_time >= StaTime && data_time <= EndTime)
                    {
                        //添加白班数据
                        list_DayShift.Add(Content);
                    }
                }
                //记录生产型号
                List<string> list_Name = new List<string>();
                for (int i = 0; i < list_DayShift.Count; i++)
                {
                    if (i == 0)
                    {
                        list_Name.Add(list_DayShift[i]);//添加第一个型号
                    }
                    else
                    {
                        if (list_DayShift[i].Split(',')[1] != list_DayShift[i - 1].Split(',')[1])
                        {
                            list_Name.Add(list_DayShift[i]);//记录白班生产多个型号
                        }
                    }
                }

                int TotalQuantity = 0;
                int TotalNumber = 0;
                for (int i2 = 0; i2 < list_Name.Count; i2++)
                {
                    //白班同一个型号的所有记录
                    List<string> list_content = new List<string>();
                    for (int i3 = 0; i3 < list_DayShift.Count; i3++)//找出list_DayShift里面的list_Name[i]型号的所有记录
                    {
                        if (list_Name[i2].Split(',')[1] == list_DayShift[i3].Split(',')[1])//如果等于list_Nmae[i]的型号记录添加到list_content里面
                        {
                            list_content.Add(list_DayShift[i3]);
                        }
                    }
                    int dex = 0;
                    //判断同一个型号里面是不是有多次生产
                    if (ModelJudgment(list_content) > 0)
                    {
                        List<string> lsit_Total = GetTotal(list_content);//获取同一个型号多次生产的最后一条数据
                        foreach (var item in lsit_Total)
                        {
                            if (int.TryParse(item.Split(',')[3], out dex) && int.TryParse(item.Split(',')[4], out dex))//判断值是否可以转换成int类型
                            {
                                TotalQuantity = TotalQuantity + int.Parse(item.Split(',')[3]);//将每次生产的数据进行相加
                                TotalNumber = TotalNumber + int.Parse(item.Split(',')[4]);//将每次生产的数据进行相加
                            }
                        }
                    }
                    else
                    {
                        if (int.TryParse(list_content[list_content.Count - 1].Split(',')[3], out dex) && int.TryParse(list_content[list_content.Count - 1].Split(',')[4], out dex))//判断值是否可以转换成int类型
                        {
                            TotalQuantity = TotalQuantity + int.Parse(list_content[list_content.Count - 1].Split(',')[3]);//将每次生产的数据进行相加
                            TotalNumber = TotalNumber + int.Parse(list_content[list_content.Count - 1].Split(',')[4]);//将每次生产的数据进行相加
                        }
                    }
                }
                ymh_DayNightShifts_model DayNightShifts = new ymh_DayNightShifts_model();
                DayNightShifts.MachineName = ymh_MachineName;
                DayNightShifts.TimePeriod = "白班";
                DayNightShifts.TotalQuantity = TotalQuantity;
                DayNightShifts.TotalNumber = TotalNumber;
                DayNightShifts.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                if (DayNightShifts.TotalQuantity != 0 || DayNightShifts.TotalNumber != 0)
                {
                    await readWrite.InsertDatabase(DayNightShifts, "ymh_DayNightShifts");
                }
            }
            OperationLog("线程5运行中(ymh白班)", textBox2);
        }

        /// <summary>
        /// 夜班
        /// </summary>
        /// <returns></returns>
        private async Task GetNightShiftData()
        {
            //记录夜班时间段的数据内容
            List<string> list_NightShift = new List<string>();
            //获取当天记录文件
            List<string> list_ymh_NightFileName = GetymhNightShiftFilePath();
            //获取前一天的记录文件
            List<string> list_ymh_WhiteFileName = GetymhFilePath();
            //机台名称
            string ymh_MachineName = "";

            for (int i = 0; i < list_ymh_NightFileName.Count; i++)
            {
                list_NightShift.Clear();
                //读取文件内容
                string[] ymh_Content = File.ReadAllLines(list_ymh_NightFileName[i], Encoding.GetEncoding("GBK"));
                //获取机台名称
                ymh_MachineName = "雅马哈_" + Path.GetFileName(list_ymh_NightFileName[i]).Split('-')[0];
                //筛选夜班的生产记录
                foreach (var Content in ymh_Content)
                {
                    DateTime StaTime = DateTime.Parse(DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd 21:00:00"));//夜班开始时间
                    DateTime EndTime = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd 08:00:00"));//夜班结束时间
                    DateTime data_time = DateTime.Parse(Content.Split(',')[6]);//文件的记录时间
                    if (data_time >= StaTime && data_time <= EndTime)
                    {
                        list_NightShift.Add(Content);//添加到list中
                    }
                }
                GetNightShiftRecordContent(list_ymh_WhiteFileName[i], list_NightShift);//获取夜班的数据记录
                //筛选出有几个产品类型
                List<string> list_Name = new List<string>();//生产的类型名称
                for (int i2 = 0; i2 < list_NightShift.Count; i2++)
                {
                    if (i2 == 0)
                    {
                        list_Name.Add(list_NightShift[i2]);
                    }
                    else
                    {
                        if (list_NightShift[i2].Split(',')[1] != list_NightShift[i2 - 1].Split(',')[1])
                        {
                            list_Name.Add(list_NightShift[i2]);
                        }
                    }
                }
                int TotalQuantity = 0;
                int TotalNumber = 0;
                for (int i2 = 0; i2 < list_Name.Count; i2++)
                {
                    List<string> list_content = new List<string>();
                    for (int i3 = 0; i3 < list_NightShift.Count; i3++)
                    {
                        if (list_Name[i2].Split(',')[1] == list_NightShift[i3].Split(',')[1])
                        {
                            list_content.Add(list_NightShift[i3]);
                        }
                    }
                    int value = 0;
                    if (ModelJudgment(list_content) > 0)//判断同一种的产品类型是否生产的次数
                    {
                        List<string> lsit_Total = GetTotal(list_content);
                        foreach (var item in lsit_Total)
                        {
                            if (int.TryParse(item.Split(',')[3], out value) && int.TryParse(item.Split(',')[4], out value))//判断是否可以转换成int类型
                            {
                                string value2 = item.Split(',')[3];
                                TotalQuantity = TotalQuantity + int.Parse(item.Split(',')[3]);
                                TotalNumber = TotalNumber + int.Parse(item.Split(',')[4]);
                            }
                        }
                    }
                    else
                    {
                        if (int.TryParse(list_content[list_content.Count - 1].Split(',')[3], out value) && int.TryParse(list_content[list_content.Count - 1].Split(',')[4], out value))//判断是否可以转换成int类型
                        {
                            TotalQuantity = TotalQuantity + int.Parse(list_content[list_content.Count - 1].Split(',')[3]);
                            TotalNumber = TotalNumber + int.Parse(list_content[list_content.Count - 1].Split(',')[4]);
                        }
                    }
                }

                ymh_DayNightShifts_model time_Data = new ymh_DayNightShifts_model();
                time_Data.MachineName = ymh_MachineName;//机台的类型
                time_Data.TimePeriod = "夜班";
                time_Data.TotalQuantity = TotalQuantity;//生产的板数
                time_Data.TotalNumber = TotalNumber;//总点数
                time_Data.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//获取当前的时间
                if (time_Data.TotalQuantity != 0 || time_Data.TotalNumber != 0)//判断记录的数据是否是0，0的话就不用写入数据库
                {
                    await readWrite.InsertDatabase(time_Data, "ymh_DayNightShifts");//写入数据库
                }
            }
            OperationLog("线程6运行中(ymh夜班)", textBox2);
        }

        private List<string> GetymhNightShiftFilePath()
        {
            List<string> list_ymh_Documents = new List<string>();
            //判断文件夹是否存在
            if (!Directory.Exists(ymh_FilePath)) return list_ymh_Documents;
            //读取文件夹的子目录
            string[] ymh_ModelName = Directory.GetDirectories(ymh_FilePath);
            foreach (var ModelName in ymh_ModelName)
            {
                //获取文件夹的名称
                string str_date = ModelName.Replace("\\", ";").Split(';')[ModelName.Replace("\\", ";").Split(';').Length - 1];
                //判断是否是当昨天的日期
                if (str_date == DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"))
                {
                    //获取文件夹的文件
                    string[] FileName = Directory.GetFiles(ModelName);
                    if (FileName.Length > 6) 
                    {
                        DeleteFile(FileName, str_date);
                    }
                    foreach (var name in FileName)
                    {
                        //将文件名称位置添加到list
                        list_ymh_Documents.Add(name);
                    }
                }
            }
            return list_ymh_Documents;
        }


        private void DeleteFile(string[] FileName,string date)
        {
            foreach (var item in FileName)
            {
                string name = Path.GetFileName(item);
                name = name.Split('-')[1].Split('.')[0];
                DateTime dt = DateTime.ParseExact(name, "yyyyMMdd", null);
                DateTime dt2 = DateTime.Parse(date);
                if (dt.Date!= dt2.Date)
                {
                    File.Delete(item);
                }
            }
        }

        private int ModelJudgment(List<string> list_Content)
        {
            int int_dex = 0;
            for (int i = 0; i < list_Content.Count; i++)
            {
                try
                {
                    int Quantity = int.Parse(list_Content[i].Split(',')[3]);
                    int Number = int.Parse(list_Content[i].Split(',')[4]);
                    if (Quantity == 0 && Number == 0)
                    {
                        Quantity = int.Parse(list_Content[i + 1].Split(',')[3]);
                        Number = int.Parse(list_Content[i + 1].Split(',')[4]);
                        if (Quantity == 0 && Number == 0)
                        {
                            int_dex++;
                        }
                    }
                }
                catch (Exception)
                {
                    continue;
                }

            }
            return int_dex;

        }

        private List<string> GetTotal(List<string> list_Content)
        {
            List<string> list_Order = new List<string>();
            for (int i = 1; i < list_Content.Count; i++)
            {
                try
                {
                    int Quantity = int.Parse(list_Content[i].Split(',')[3]);
                    int Number = int.Parse(list_Content[i].Split(',')[4]);
                    if (Quantity == 0 && Number == 0)
                    {
                        if (int.Parse(list_Content[i - 1].Split(',')[3]) != 0)
                        {
                            list_Order.Add(list_Content[i - 1]);
                        }
                    }
                    if (i == list_Content.Count-1)
                    {
                        if (list_Order.Count==0)
                        {
                            list_Order.Add(list_Content[i - 1]);
                        }
                        else if (list_Order[list_Order.Count-1].Split(',')[6]!= list_Content[i - 1].Split(',')[6])
                        {
                            list_Order.Add(list_Content[i - 1]);
                        }
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            return list_Order;
        }

        private void GetNightShiftRecordContent(string filepath, List<string> NightShift)
        {
            string[] ymh_Content = File.ReadAllLines(filepath, Encoding.GetEncoding("GBK"));
            foreach (var Content in ymh_Content)
            {
                try
                {
                    DateTime StaTime = DateTime.Parse(DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd 21:00:00"));
                    DateTime EndTime = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd 08:00:00"));
                    DateTime data_time = DateTime.Parse(Content.Split(',')[6]);
                    if (data_time >= StaTime && data_time <= EndTime)
                    {
                        NightShift.Add(Content);
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }

        #endregion

        #region 机台电力使用情况
        private async Task GKG_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from gkg_Producedate WHERE CAST(TimeStamp AS DATE)=CAST(GETDATE() AS DATE)";
                    List<gkg_model> list_gkg = await readWrite.QueryDataAsync<gkg_model>(query);
                    List<string> machineNames = await readWrite.SelectDataAsync("gkg_Producedate", "TimeStamp");
                    List<double> gkg_Time = gkg_CycleTime(list_gkg, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "GKG印刷机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = gkg_Time[i];
                            electricity.Powers = 2.2;
                            electricity.PowerLevel = gkg_Time[i] * 2.2;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("GKG印刷机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    ErrorRecord(ex.ToString() + "      " + "gkg机台电力使用情况");
                    continue;
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> gkg_CycleTime(List<gkg_model> list_gkg, List<string> machineNames)
        {
            List<double> time = new List<double>();
            TimeSpan timeSpan = TimeSpan.FromSeconds(0);
            for (int i = 0; i < machineNames.Count; i++)
            {
                List<gkg_model> gkg = list_gkg.Where(t => t.MachineName == machineNames[i]).ToList();
                timeSpan= TimeSpan.FromSeconds(0);
                foreach (var g in gkg)
                {
                    timeSpan += TimeSpan.FromSeconds(int.Parse(g.CycleTime));
                }
                time.Add(timeSpan.TotalHours);
            }
            return time;
        }

        private async Task YMH_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from ymh_Producedate where CAST(Time as date)=CAST(GETDATE() as date)";
                    List<ymh_model> list_ymh = await readWrite.QueryDataAsync<ymh_model>(query);
                    List<string> machineNames = await readWrite.SelectDataAsync("ymh_Producedate", "Time");
                    List<double> ymh_Time = ymh_CycleTime(list_ymh, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "雅马哈";
                            electricity.Model = machineNames[i].Split('_')[1];
                            electricity.Runtime = ymh_Time[i];
                            electricity.Powers = 2.2;
                            electricity.PowerLevel = ymh_Time[i] * 2.2;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("雅马哈 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    ErrorRecord(ex.ToString() + "      " + "ymh机台电力使用情况");
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> ymh_CycleTime(List<ymh_model> list_ymh, List<string> machineNames)
        {
            List<double> time = new List<double>();
            TimeSpan timeSpan = TimeSpan.Parse("0");
            for (int i = 0; i < machineNames.Count; i++)
            {
                timeSpan = TimeSpan.Parse("0");
                List<ymh_model> ymh = list_ymh.Where(t => t.MachineName == machineNames[i]).ToList();
                for (int j = 0; j < ymh.Count-1; j++)
                {
                    if (ymh[j].NumberBoards == ymh[j + 1].NumberBoards) continue;
                    timeSpan += DateTime.Parse(ymh[j + 1].Time) - DateTime.Parse(ymh[j].Time);
                }
                time.Add(timeSpan.TotalHours);
            }
            return time;
        }

        private async Task JUKI_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from juki_Producedate WHERE CAST(StopTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<juki_model> list_juki = await readWrite.QueryDataAsync<juki_model>(query);
                    List<string> machineNames = await readWrite.SelectDataAsync("juki_Producedate", "StopTime");
                    List<double> juki_Time = juki_CycleTime(list_juki, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "juki贴片机";
                            electricity.Model = machineNames[i].Split(' ')[1];
                            electricity.Runtime = juki_Time[i];
                            electricity.Powers = 6.2;
                            electricity.PowerLevel = juki_Time[i] * 6.2;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("juki贴片机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    ErrorRecord(ex.ToString() + "      " + "juki机台电力使用情况");
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> juki_CycleTime(List<juki_model> juki_Models, List<string> machineNames)
        {
            List<double> time = new List<double>();
            TimeSpan CycleTime = TimeSpan.Parse("0");
            for (int i = 0; i < machineNames.Count; i++)
            {
                List<juki_model> juki = juki_Models.Where(t=>t.MachineName== machineNames[i]).ToList();
                foreach (var jk in juki)
                {
                    CycleTime += TimeSpan.Parse(jk.RunningTime);
                }
                time.Add(CycleTime.TotalHours);
            }
            return time;
        }

        private async Task HL_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from hl_Producedate WHERE CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<hl_model> list_hl = await readWrite.QueryDataAsync<hl_model>(query);
                    List<string> machineNames = await readWrite.SelectDataAsync("hl_Producedate", "logTime");
                    List<double> hl_Time = hl_CycleTime(list_hl, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "回流焊接机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = hl_Time[i];
                            electricity.Powers = 86;
                            electricity.PowerLevel = hl_Time[i] * 86;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("回流焊接机 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await HL_PowerDataUpload();
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> hl_CycleTime(List<hl_model> hl_Models, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<hl_model> list_MachineTime = hl_Models.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    if (list_MachineTime[i].Machine == "冷却模式") continue;
                    machineTimeSpan += currentTime - previousTime;
                }
                time.Add(machineTimeSpan.TotalHours);
            }
            return time;
        }
        #endregion

        #region 数据统计

        private async Task DataAnalysis()
        {
            List<string> list_MachineName = new List<string>() { "GKG自动印刷机", "JUKI贴片机" , "回流焊接机","雅马哈贴片机"};
            while (true)
            {
                int index = 0;
                foreach (var MachineName in list_MachineName)
                {
                    try
                    {
                        //启动时间
                        string BTime = await BootTime(MachineName, false);
                        //运行时间
                        string RTime = await BootTime(MachineName, true);
                        double rTimeTotalSeconds = ParseTimeToTotalSeconds(RTime);
                        double bTimeTotalSeconds = ParseTimeToTotalSeconds(BTime);
                        if (BTime == "00:00:00" || RTime == "00:00:00") continue;
                        //运行时间
                        string DTime = FormatTimeSpan(ParseExtendedTimeSpan(BTime) - ParseExtendedTimeSpan(RTime));
                        //稼动率
                        string utilizationRate = (rTimeTotalSeconds / bTimeTotalSeconds).ToString("P2");
                        //生产数量
                        int Total = await ProductionQuantity(MachineName);
                        if (RTime == "00:00:00") utilizationRate = "0.00%";
                        Statistic list_statistic = new Statistic()
                        {
                            MachineName = MachineName,
                            EquipmentTotal = GetMachineNumber(MachineName),
                            OnlineQuantity = await OnlineQuantity(MachineName),
                            BootTime = BTime,
                            Runtime = RTime,
                            Downtime = DTime,
                            UtilizationRate = utilizationRate,
                            Output = Total,
                            logTime = DateTime.Now.ToString()
                        };
                        string query = $"select * from Statistic where MachineName='{MachineName}' and CAST(logTime as date)=CAST(GETDATE() as date)";
                        if (await readWrite.SelectData(query) == true)
                        {
                            await readWrite.UpdateDate(list_statistic, query, "Statistic");
                            OperationLog($"更新数据统计表  1条数据", textBox1);
                        }
                        else
                        {
                            await readWrite.InsertDatabase(list_statistic, "Statistic");
                            OperationLog($"插入数据统计表  1条数据", textBox1);
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorRecord(ex.ToString() + "      " + "数据统计");
                        continue;
                    }
                    index++;
                }
                await Task.Delay(600000);
            }
        }

        private async Task<string> BootTime(string MachineName, bool run)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    string gkg_query = "select * from gkg_Producedate where CAST(TimeStamp as date)=CAST(GETDATE() as date)";
                    List<gkg_model> list_gkg = await readWrite.QueryDataAsync<gkg_model>(gkg_query);
                    return GKG_TotalTime(list_gkg, run);
                case "JUKI贴片机":
                    string juki_query = "select * from juki_Producedate where CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<juki_model> list_juki = await readWrite.QueryDataAsync<juki_model>(juki_query);
                    return JUKI_TotalTime(list_juki, run);
                case "回流焊接机":
                    string hl_query = "select * from hl_Producedate where CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<hl_model> list_hl = await readWrite.QueryDataAsync<hl_model>(hl_query);
                    return HL_TotalTime(list_hl, run);
                case "雅马哈贴片机":
                    string ymh_query = "select * from ymh_Producedate WHERE CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<ymh_model> list_ymh = await readWrite.QueryDataAsync<ymh_model>(ymh_query);
                    return YMH_TotalTime(list_ymh, run);
                default:
                    return "";
            }
        }

        private string GKG_TotalTime(List<gkg_model> list_gkg, bool run)
        {
            try
            {
                if (list_gkg == null || list_gkg.Count == 0) return "";
                TimeSpan PauseTime = TimeSpan.Parse("00:05:00");
                List<string> machineName = list_gkg.Select(t => t.MachineName).Distinct().ToList();
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                foreach (var Name in machineName)
                {
                    List<gkg_model> list_MachineTime = list_gkg.Where(t => t.MachineName == Name).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].TimeStamp);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].TimeStamp);
                        if (currentTime - previousTime > PauseTime && run) continue;
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception)
            {
                return "00:00:00";
            }
        }

        private string JUKI_TotalTime(List<juki_model> juki_Models, bool run)
        {
            if (run)
            {
                try
                {
                    TimeSpan CycleTime = TimeSpan.Parse("0");
                    foreach (var juki in juki_Models)
                    {
                        CycleTime += TimeSpan.Parse(juki.RunningTime);
                    }
                    return FormatTimeSpan(CycleTime);
                }
                catch (Exception)
                {
                    return "00:00:00";
                }

            }
            else
            {
                try
                {
                    TimeSpan CycleTime = TimeSpan.Parse("0");
                    foreach (var juki in juki_Models)
                    {
                        CycleTime += TimeSpan.Parse(juki.RunningTime) + TimeSpan.Parse(juki.PwbWaitTime);
                    }
                    return FormatTimeSpan(CycleTime);
                }
                catch (Exception)
                {
                    return "00:00:00";
                }
            }
        }

        private string HL_TotalTime(List<hl_model> hls, bool run)
        {
            try
            {
                if (hls == null || hls.Count == 0) return "";
                TimeSpan PauseTime = TimeSpan.Parse("00:11:00");
                List<string> machineNames = hls.Select(t => t.MachineName).Distinct().ToList();
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                foreach (var Machine in machineNames)
                {
                    List<hl_model> list_MachineTime = hls.Where(t => t.MachineName == Machine).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                        if (currentTime - previousTime > PauseTime && run) continue;
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception)
            {
                return "00:00:00";
            }

        }

        private string YMH_TotalTime(List<ymh_model> list_ymh,bool run)
        {
            List<string> machineName = list_ymh.Select(t => t.MachineName).Distinct().ToList();
            TimeSpan totalTimeSpan = TimeSpan.Zero;
            foreach (var Name in machineName)
            {
                List<ymh_model> list_MachineTime = list_ymh.Where(t => t.MachineName == Name).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count - 1; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].Time);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].Time);
                    if (list_MachineTime[i].Cycle == 0 && run) continue;
                    machineTimeSpan += currentTime - previousTime;
                }
                totalTimeSpan += machineTimeSpan;
            }
            return FormatTimeSpan(totalTimeSpan);
        }

        private async Task<int> ProductionQuantity(string MachineName)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    string gkg_query = "select * from gkg_Producedate where CAST(TimeStamp as date)=CAST(GETDATE() as date)";
                    List<gkg_model> list_gkg = await readWrite.QueryDataAsync<gkg_model>(gkg_query);
                    return GKG_TotalNumberProducts(list_gkg);
                case "JUKI贴片机":
                    string juki_query = "select * from juki_Producedate where CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<juki_model> list_juki = await readWrite.QueryDataAsync<juki_model>(juki_query);
                    return JUKI_TotalNumberProducts(list_juki);
                case "回流焊接机":
                    return 0;
                case "雅马哈贴片机":
                    string ymh_query = "select * from ymh_Producedate WHERE CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<ymh_model> list_ymh = await readWrite.QueryDataAsync<ymh_model>(ymh_query);
                    return YMH_TotalNumberProducts(list_ymh);
                default:
                    return 0;
            }
        }

        private int GKG_TotalNumberProducts(List<gkg_model> list_gkg)
        {
            List<string> MachineNames = list_gkg.Select(t => t.MachineName).Distinct().ToList();
            int total = 0;
            foreach (string MachineName in MachineNames)
            {
                List<gkg_model> GKG = list_gkg.Where(t => t.MachineName == MachineName).ToList();
                if (GKG.Count == 0) continue;
                total += GKG[GKG.Count - 1].PCBNumber;
            }
            return total;
        }

        private int JUKI_TotalNumberProducts(List<juki_model> juki_Models)
        {
            int TotalNumber = 0;
            foreach (var juki in juki_Models)
            {
                TotalNumber += Convert.ToInt32(juki.TotalPick);
            }
            return TotalNumber;
        }

        private int YMH_TotalNumberProducts(List<ymh_model> list_ymh) 
        {
            List<string> MachineNames = list_ymh.Select(t => t.MachineName).Distinct().ToList();
            int list_Total = 0;
            int TotalQuantity = 0;
            for (int i = 0; i < MachineNames.Count; i++)
            {
                List<ymh_model> ymhs = list_ymh.Where(t => t.MachineName == MachineNames[i]).ToList();
                TotalQuantity = 0;
                for (int j = 1; j < list_ymh.Count; j++)
                {
                    try
                    {
                        if (list_ymh[j].TotalQuantity == "") continue;
                        if (list_ymh[j].TotalQuantity == "0") TotalQuantity += int.Parse(list_ymh[j - 1].TotalQuantity);
                        if (j == list_ymh.Count - 1) TotalQuantity += int.Parse(list_ymh[j].TotalQuantity);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
                list_Total += TotalQuantity;
            }
            return list_Total;
        }

        private string FormatTimeSpan(TimeSpan timeSpan)
        {
            int totalHours = (int)timeSpan.TotalHours;
            int minutes = timeSpan.Minutes;
            int seconds = timeSpan.Seconds;
            // 格式化为“小时:分钟:秒”，小时数可以超过24
            return $"{totalHours:D2}:{minutes:D2}:{seconds:D2}";
        }

        public static double ParseTimeToTotalSeconds(string timeString)
        {
            string[] parts = timeString.Split(':');
            if (parts.Length != 3)
            {
                throw new FormatException("时间格式应为 HH:mm:ss");
            }

            int hours = int.Parse(parts[0]);
            int minutes = int.Parse(parts[1]);
            int seconds = int.Parse(parts[2]);

            // 计算总秒数
            return hours * 3600 + minutes * 60 + seconds;
        }

        private static TimeSpan ParseExtendedTimeSpan(string timeString)
        {
            try
            {
                string[] parts = timeString.Split(':');
                if (parts.Length != 3)
                {
                    throw new FormatException("时间格式必须为HH:mm:ss");
                }

                int hours = int.Parse(parts[0]);
                int minutes = int.Parse(parts[1]);
                int seconds = int.Parse(parts[2]);

                // 验证分钟和秒数是否在有效范围内
                if (minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59)
                {
                    throw new ArgumentOutOfRangeException("分钟或秒数必须在0-59之间");
                }

                // 使用构造函数创建TimeSpan，支持超过24小时的小时数
                return new TimeSpan(hours, minutes, seconds);
            }
            catch (Exception ex)
            {
                throw new FormatException($"无法解析时间字符串 '{timeString}': {ex.Message}");
            }
        }

        public int GetMachineNumber(string Name)
        {
            int Number = 0;
            switch (Name)
            {
                case "GKG自动印刷机":
                    return Number = 12;
                case "JUKI贴片机":
                    return Number = 3;
                case "回流焊接机":
                    return Number = 3;
                case "雅马哈贴片机":
                    return Number = 6;
                default:
                    return Number;
            }
        }

        private async Task<int> OnlineQuantity(string MachineName)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    return await readWrite.SelectDataAsyncCategory("gkg_Producedate", "TimeStamp");
                case "JUKI贴片机":
                    return await readWrite.SelectDataAsyncCategory("juki_Producedate", "Time");
                case "回流焊接机":
                    return await readWrite.SelectDataAsyncCategory("hl_Producedate", "logTime");
                case "雅马哈贴片机":
                    return await readWrite.SelectDataAsyncCategory("ymh_Producedate", "Time");
                default:
                    break;
            }
            return 0;
        }

        #endregion

        /// <summary>
        /// 程序运行状态显示(显示线程是否在运行，数据写入数据库的记录)
        /// </summary>
        /// <param name="content"></param>
        /// <param name="text"></param>
        private void OperationLog(string content, TextBox text)
        {
            Invoke(new EventHandler(delegate
            {
                text.AppendText($"{content} {DateTime.Now.ToString()}\r\n");
                textBox1.SelectionStart = textBox1.Text.Length;
            }));
        }

        public static void ErrorRecord(string Content)
        {
            if (!Directory.Exists("Log\\"))
            {
                Directory.CreateDirectory("Log\\");
            }
            using (StreamWriter sw = new StreamWriter("Log\\log.txt", true))
            {
                sw.WriteLine(Content);

            }
        }

        /// <summary>
        /// 显示界面只显示1000条记录
        /// </summary>
        /// <returns></returns>
        private async Task TextBoxContent()
        {
            while (true)
            {
                Invoke(new EventHandler(delegate
                {
                    string[] ArrayLog1 = textBox1.Text.Replace("\r\n", "/").Split('/');
                    string[] ArrayLog2 = textBox2.Text.Replace("\r\n", "/").Split('/');
                    if (ArrayLog1.Length > 1000)
                    {
                        Invoke(new EventHandler(delegate { textBox1.Text = ""; }));
                    }
                    if (ArrayLog2.Length > 1000)
                    {
                        Invoke(new EventHandler(delegate { textBox2.Text = ""; }));
                    }
                }));
                await Task.Delay(2000);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            
            if (NightShiftTime() == true){
                _ = GetDayShiftData();//白班
                
            }
            else {
                _ = GetNightShiftData();//夜班
            }
        }

        private bool NightShiftTime()
        {
            TimeSpan NightShiftTime = TimeSpan.Parse("21:00");
            TimeSpan DayShift= TimeSpan.Parse("08:00");
            TimeSpan span = DateTime.Now.TimeOfDay;
            if (span <= NightShiftTime && span >= DayShift) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
